<?php

class NewsService extends Service_Base implements ISingleton 
{
	/**
	 *
	 * @var NewsService
	 */
	private static $_instance;
	
	/**
	 *
	 * @return NewsService
	 */
	public static function getInstance()
	{
		if (!self::$_instance) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}			
	
	/**
	 * Function for getting any select from news table
	 * @param NewsCriteria $criteria
	 * @return Db_Select;
	 */
	public function getNewsSelect(NewsCriteria $criteria)
	{
		$peer = NewsPeer::getInstance();
		$select = $peer->select();
		$startDate = $criteria->getDateStart();
		$endDate = $criteria->getDateEnd();
		// get join with tags
		$tags = $criteria->getTags();
		if ($tags) {
			foreach ($tags as $tagId) {
				$select->join('news2tag', NewsPeer::ID . '=' . News2tagPeer::NEWS_ID, array());
				$select->where(News2tagPeer::TAG_ID, $tagId);
			}
		}
		// add time constraints
		if ($startDate && $endDate) {
			$select->where('`date` >= ?', $startDate);
			$select->where('`date` <= ?', $endDate);
		} elseif ($startDate) {
			$select->where(NewsPeer::DATE, $startDate);
		}
		
		$limit = $criteria->getLimit();
		$page = $criteria->getPage();
		if ($limit) {
			$select->limitPage($page, $limit);
		}
		$order = $criteria->getOrder();
		if ($order) {
			$orderTYpe = $criteria->getOrderType();
			$select->order("$order $orderTYpe");
		}
		return $select;
	}
	
	public function getShortNewsList()
	{
		// get list of short news
		$newsSelect = NewsShortPeer::getInstance()->select()->limit(10)->order('date');
		$newsRowset = NewsShortPeer::getInstance()->fetchAll($newsSelect);
		return $newsRowset;
		
	}
	

}